from flask import Flask, render_template, request, jsonify, flash, redirect, url_for
import base64, random, datetime, json, os
import face_recognition
from utils import make_file, RemoveDir, NpEncoder

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/index')
def index():
    return render_template('index.html')


@app.route('/login', methods=['GET','POST'])
def login():
    if request.method == 'POST':
        res = request.get_json().get('data')
        username = res.get('username')
        password = res.get('password')
        src = res.get('src')
        pop_src = res.pop('src')
        if username and password and pop_src:
            login_path = 'static/face_data_login'
            RemoveDir( login_path  )
            data = pop_src.split('base64,')[-1]
            image_data = base64.b64decode(data)
            with open('%s/%s.png' % (login_path, username), 'wb') as f:
                f.write(image_data)

            path = os.path.join('static/face_data_register', username)
            if os.path.exists(path): #如果有这个目录，证明有这个账号
                contents = os.listdir(path)
                img_all = []
                username_json = {}
                username_json_fileName = ''
                for i in contents:
                    if os.path.splitext(i)[1] == '.png':
                        img_all.append(i)
                    elif os.path.splitext(i)[1] == '.json':
                        username_json_fileName = i
                        with open('%s/%s' % (path, i) , 'r') as f:
                            username_json = json.loads(f.read())

                print(img_all)
                print(username_json)
                picture_of_me = username_json.get('face_image_data') # 提取特征数据
                # 打开登陆截图
                loa_img = os.path.join( login_path, username + '.png')
                unknown_picture = face_recognition.load_image_file( loa_img )
                face_recognition_res = face_recognition.face_encodings(unknown_picture)
                if not face_recognition_res:
                    print('未识别到人脸面部信息！！！有遮挡物')
                    return jsonify({"code": 0, 'news': '未识别到人脸面部信息！！！' })

                results = face_recognition.compare_faces([picture_of_me], face_recognition_res[0], tolerance=0.45)

                # 判断账号密码
                if username == username_json['username'] and password == username_json['password']:
                    print('账号密码正确')
                    if results[0] == True:
                        print("人脸识别成功")
                        return jsonify({"code": 200, 'url': 'index', 'news':'人脸验证通过，登陆成功'})
                    else:
                        print("人脸识别失败")
                        return jsonify({"code": 0, 'url': '', 'news':'人脸验证不通过'})
                else:
                    return jsonify({'code':0, 'url':'','news':'账号密码错误!!'})

    return render_template('login.html')




@app.route('/paizhao')
def paizhao():

    return render_template('paizhao.html')





@app.route('/jieshou', methods=['POST'])
def jieshou():
    # flash('用户%s添加成功！', 'success')
    src = request.get_json().get('data')
    data = src.split('base64,')[-1]
    image_data = base64.b64decode(data)
    name = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
    with open('./static/face_data_register/%s.png' % name, 'wb') as f:
        f.write(image_data)
    return 'ok'

# 注册
@app.route('/register', methods=['POST'])
def register():
    # 账号 密码 头像 同时保存在以账号为主的目录内
    res = request.get_json().get('data')
    if res:
        username = res['username']
        src = res['src']
        res.pop('src')
        path = os.path.join( 'static/face_data_register' , username)
        make_file(path)

        data = src.split('base64,')[-1]
        image_data = base64.b64decode(data)

        # img = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        #保存图片
        with open('%s/%s.png' % (path, username), 'wb') as f:
            f.write(image_data)
        picture_of_me = face_recognition.load_image_file( os.path.join(path, username+'.png') )
        face_image_data = face_recognition.face_encodings(picture_of_me)
        if face_image_data:
            res['face_image_data'] = face_image_data[0] #获取第一个人脸
        else:
            print('未获取到人脸')
            RemoveDir( path )
            return  jsonify( {"code": 0, "news":"未获取到人脸,请重新录入注册"})
        #保存账号密码
        with open('%s/%s.json'% (path, username) , 'w') as file:
            file.write( json.dumps(res, cls=NpEncoder) )
        return jsonify({"code": 200, "news":"恭喜，用户 %s 注册成功，请牢记账号密码" % username})




if __name__ == '__main__':
    app.run(debug=True)
